package com.merak.rebot.core;

import com.merak.rebot.config.LoadConfigContext;
import com.merak.rebot.config.MRebotsConfig;
import com.merak.rebot.utils.CommonConstants;
import com.merak.rebot.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MerakRebotExecutor {

	@Autowired
	private MRebotsConfig mrebotsConfig;

//	@Scheduled(cron = "0/15 * * * * ?")
	public void doExecutor() {
		log.info("[start...]");
		String path = "D:\\workspace\\merak\\MerakPlatform\\MerakJRebot\\MJReotService\\scripts\\";
		String python = "hello.py";

		BufferedReader reader = null;
		try {
			Process proc = Runtime.getRuntime().exec("python " + path + python);
			reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			String line = null;
			int lineno = 1;
			while ((line = reader.readLine()) != null) {
				log.info("{}\t{}", lineno, line);
				lineno++;
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
				log.info(e.getMessage(), e);
			}
		}

		log.info("[end.    ]");
	}

	/**
	 * 初始化目录结构
	 */
	@PostConstruct
	public void loadConfigDir(){
		log.info("loadConfigDir loading start ...");
		//初始化配置文件
		LoadConfigContext.init();
		//获取需要初始化的地址
		String dirs = LoadConfigContext.getProperties("meraktech.init.config.dirs");
		initDirs(dirs);
		log.info("loadConfigDir loading end ...");
	}

	private void initDirs(String dirs) {
		if(StringUtils.isNotEmpty(dirs)){
			String[] dirArr = dirs.split(CommonConstants.DIR_SEPARATOR);
			for (String dir : dirArr) {
				if(StringUtils.isNotEmpty(dir)&&StringUtils.isNotEmpty(dir.trim())){
					String endsDir = Arrays.stream(dir.split("\\/")).collect(Collectors.joining(File.separator));
					try {
						FileUtil.isDirectory(mrebotsConfig.getRebots().getPath()+ File.separator+endsDir);
						//使生成的目录有一定的时间差，因为后面前端读取目录是按生成的时间进行排序，避免顺序混乱
						Thread.sleep(500L);
					} catch (IOException e) {
						log.error("初始化目录失败，失败目录：{}",mrebotsConfig.getRebots().getPath()+ File.separator+endsDir);
					} catch (Exception ex){
						log.error(ex.getMessage(),ex);
					}
				}
			}
		}
	}

}
